/**
 Copyright (c) 2020-2022 宁波哥爱帮科技有限公司
 */
package cn.grab.fispservice.authentication.controller;

import cn.grab.fispapi.authentication.dto.EnterpriseAuthenticationDTO;
import cn.grab.fispapi.authentication.dto.PersonalAuthenticationDTO;
import cn.grab.fispapi.authentication.dto.SysUserAuthenticationDTO;
import cn.grab.fispapi.upms.dto.SysAddRoleDTO;
import cn.grab.fispservice.authentication.model.EnterpriseAuthentication;
import cn.grab.fispservice.authentication.model.PersonalAuthentication;
import cn.grab.fispservice.authentication.model.UserAuthentication;
import cn.grab.fispservice.authentication.service.EnterpriseAuthenticationService;
import cn.grab.fispservice.authentication.service.PersonalAuthenticationService;
import cn.grab.fispservice.authentication.service.UserAuthenticationService;
import cn.grab.fispservice.util.ThreadLocalUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fontana.base.annotation.MyRequestBody;
import com.fontana.base.result.Result;
import com.fontana.base.result.ResultCode;
import com.fontana.oss.model.ObjectInfo;
import com.fontana.oss.service.IOssService;
import com.fontana.util.validate.ValidateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.Date;
import javax.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @description 认证接口控制器
 * @author 16411
 * @date 2022/12/14 13:13
 */
@Api(tags = "用户认证接口")
@RestController
@RequestMapping("/authentication")
public class AuthenticationController {

  @Resource
  private PersonalAuthenticationService authenticationService;

  @Resource
  private UserAuthenticationService userAuthenticationService;

  @Resource
  private IOssService iOssService;

  @Resource
  private EnterpriseAuthenticationService enterpriseAuthenticationService;

  /**
   个人认证接口

   @Param: PersonalAuthenticationDTO
   @return: 应答结果 返回认证成功消息
   @Author: guji
   @date: 2022/12/14
   */
  //@ApiOperation("个人认证接口")
  //@ApiOperationSupport(ignoreParameters = {"PersonalAuthenticationDTO.Id"})
 // @PostMapping("/personal")
  public Result<String> personalAuthentication(
      @MyRequestBody PersonalAuthenticationDTO personalAuthenticationDTO) {
    //校验参数
    String message = ValidateUtil.getModelValidationError(personalAuthenticationDTO);
    if (message != null) {
      return Result.failed(ResultCode.PARAM_IS_BLANK, message);
    }

    //获取token中的userId
     Long userId = ThreadLocalUtils.get();

    //根据当前用户登录id查询当前用户是否已经认证,查询当前用户id关联的个人认证id
    LambdaQueryWrapper<UserAuthentication> eq = new LambdaQueryWrapper<UserAuthentication>().eq(
        UserAuthentication::getUserId, userId);
    UserAuthentication userAuthentication = userAuthenticationService.getOne(eq);

    //创建对象
    PersonalAuthentication personalAuthentication = new PersonalAuthentication();

    //校验查询出来的对象是否为空
    if (null == userAuthentication) {

      //克隆对象到个人实体类对象中
      BeanUtils.copyProperties(personalAuthenticationDTO, personalAuthentication);

      //当中间表的信息为空,直接创建个人认证对象,存储进数据库
      //封装请求中没有的参数
      personalAuthentication.setCreatedUserId(userId);
      personalAuthentication.setCreatedTime(new Date());
      personalAuthentication.setWhetherExamine(0);

      //调用service存储个人认证信息到数据库中
      authenticationService.save(personalAuthentication);

      //创建中间表对象
      userAuthentication=new UserAuthentication();

      //当中间表信息为空,添加中间表信息
      userAuthentication.setPersonalAuthenticationId(personalAuthentication.getId());
      userAuthentication.setUserId(userId);
      //企业已经认证过,直接设置为3
      if (userAuthentication.getEnterpriseAuthenticationId() != null){
        userAuthentication.setAuthenticationType(3);
      }else {
        userAuthentication.setAuthenticationType(1);
      }
      userAuthenticationService.save(userAuthentication);

    } else {

      //当中间表不为空,查询用户的认证信息
       personalAuthentication = authenticationService.getById(
          userAuthentication.getPersonalAuthenticationId());

       //拷贝要修改的对象到查询出来的对象中
      BeanUtils.copyProperties(personalAuthenticationDTO, personalAuthentication);

      //已经认证过,重新修改认证,封装认证信息
      //封装请求中没有的参数
      personalAuthentication.setUpdatedUserId(userId);
      personalAuthentication.setUpdatedTime(new Date());
      personalAuthentication.setWhetherExamine(0);

      //调用service 修改数据库个人认证信息
      authenticationService.updateById(personalAuthentication);


      //当中间表信息 不为空,修改中间表信息
      userAuthentication.setPersonalAuthenticationId(personalAuthentication.getId());
      userAuthentication.setUserId(userId);
      //企业已经认证过,直接设置为3
      if (userAuthentication.getEnterpriseAuthenticationId() != null){
        userAuthentication.setAuthenticationType(3);
      }else {
        userAuthentication.setAuthenticationType(1);
      }
      userAuthenticationService.updateById(userAuthentication);
    }

    return Result.failed(ResultCode.SUCCESS, "个人认证信息已提交,请等待管理员审核");
  }


  /**
   企业认证接口
   @Param: EnterpriseAuthenticationDTO
   @return: 应答结果 返回认证成功消息
   @Author: guji
   @date: 2022/12/14
   */
  //@ApiOperation("企业认证接口")
 // @PostMapping("/enterprise")
  public Result<String> enterpriseAuthentication(@MyRequestBody EnterpriseAuthenticationDTO dto,
      @RequestParam("file") MultipartFile file) {
    //校验参数
    String message = ValidateUtil.getModelValidationError(dto);
    if (message != null) {
      return Result.failed(ResultCode.PARAM_IS_BLANK, message);
    }

    //上传营业执照url,获取上传文件查看路径和保存路径
    ObjectInfo upload = iOssService.upload(file);
    String objectUrl = upload.getObjectUrl();  //文件查看路径
    String objectPath = upload.getObjectPath(); //文件保存路径

    //获取当前认证用户id
    Long userId = ThreadLocalUtils.get();

    //根据用户id查询是否已经进行企业认证
    LambdaQueryWrapper<UserAuthentication> eq = new LambdaQueryWrapper<UserAuthentication>().eq(
        UserAuthentication::getUserId, userId);
    UserAuthentication userAuthentication = userAuthenticationService.getOne(eq);

    //创建企业认证对象
    EnterpriseAuthentication enterpriseAuthentication = new EnterpriseAuthentication();

    //校验用户是否已经企业认证
    if (null == userAuthentication){
      //拷贝对象到企业认证实体类对象中
      BeanUtils.copyProperties(dto,enterpriseAuthentication);

      //封装请求中没有的参数
      enterpriseAuthentication.setBusinessSeeLicense(objectUrl);
      enterpriseAuthentication.setBusinessStorageLicense(objectPath);
      enterpriseAuthentication.setCreatedUserId(userId);
      enterpriseAuthentication.setCreatedTime(new Date());
      enterpriseAuthentication.setWhetherExamine(0);

      //调用service存储企业认证信息
      enterpriseAuthenticationService.save(enterpriseAuthentication);

      //创建中间表对象
      userAuthentication = new UserAuthentication();

      //个人认证和企业认证id都不存在,封装中间表信息,保存进数据库
      userAuthentication.setUserId(userId);
      userAuthentication.setEnterpriseAuthenticationId(enterpriseAuthentication.getId());

      //中间表中没有个人认证id,设置认证类型为企业认证
      if (userAuthentication.getPersonalAuthenticationId() != null){
          userAuthentication.setAuthenticationType(3);
      }else {
          userAuthentication.setAuthenticationType(2);
      }


      userAuthenticationService.save(userAuthentication);


    } else {

      //根据中间表信息查询企业认证信息
       enterpriseAuthentication = enterpriseAuthenticationService.getOne("id",
          userAuthentication.getEnterpriseAuthenticationId());

      //拷贝对象到企业认证实体类对象中
      BeanUtils.copyProperties(dto,enterpriseAuthentication);

      //封装请求中没有的参数
      enterpriseAuthentication.setBusinessSeeLicense(objectUrl);
      enterpriseAuthentication.setBusinessStorageLicense(objectPath);
      enterpriseAuthentication.setUpdatedUserId(userId);
      enterpriseAuthentication.setUpdatedTime(new Date());
      enterpriseAuthentication.setWhetherExamine(0);

      //调用service存储企业认证信息
      enterpriseAuthenticationService.updateById(enterpriseAuthentication);

      //个人认证或企业认证信息存在
      userAuthentication.setUserId(userId);
      userAuthentication.setEnterpriseAuthenticationId(enterpriseAuthentication.getId());
      //中间表中没有个人认证id,设置认证类型为企业认证
      if (userAuthentication.getPersonalAuthenticationId() != null){
        userAuthentication.setAuthenticationType(3);
      }else {
        userAuthentication.setAuthenticationType(2);
      }

      userAuthenticationService.updateById(userAuthentication);
    }

    return Result.failed(ResultCode.SUCCESS, "企业认证信息已提交,请等待管理员审核");
  }

  /**
   个人认证数据回显接口
   @Param:
   @return: 应答结果 个人认证信息
   @Author: guji
   @date: 2022/12/14
   */
  //@ApiOperation("个人认证数据回显接口")
  //@GetMapping("/echoPersonalAuthentication")
  public Result<Object> echoPersonalAuthentication(){
   return authenticationService.findPersonalAuthentication();
  }

  /**
   企业认证数据回显接口
   @Param:
   @return: 应答结果 企业认证信息
   @Author: guji
   @date: 2022/12/14
   */
 // @ApiOperation("企业认证数据回显接口")
 // @GetMapping("/echoEnterpriseAuthentication")
  public Result<Object> echoEnterpriseAuthentication(){
    return enterpriseAuthenticationService.findEnterpriseAuthentication();
  }

  /**
      运营部平台认证审核用户认证信息接口
   @Param:
   @return: 应答结果 审核消息通知
   @Author: guji
   @date: 2022/12/14
   */
  @PostMapping("/examineAuthentication")
  public Result<Object> examineAuthentication(Long userId,Integer status){
    //校验参数
    if (StringUtils.isEmpty(status)){
       return Result.failed(ResultCode.PARAM_NOT_COMPLETE);
    }
    return userAuthenticationService.toExamineAuthentication(userId,status);
  }

  /**
    认证审核接口回显,展示用户列表
   @Param:
   @return: 应答结果 已认证未审核用户列表
   @Author: guji
   @date: 2022/12/14
   */
  @PostMapping("/authenticationEcho")
  public Result<Object> authenticationEcho(@MyRequestBody SysUserAuthenticationDTO sysUserAuthenticationDTO){
   return userAuthenticationService.findIsAuthentication(sysUserAuthenticationDTO);
  }


  /**
    用户认证接口 ,
   *@Param: SysAddRoleDTO 选择的角色id  ,PersonalAuthenticationDTO 个人认证信息 ,EnterpriseAuthenticationDTO 企业认证信息 ,MultipartFile 上传文件
   *@return: 认证成功应答消息
   *@Author: xxxx
   *@date: 2022/12/28
   */
  @ApiOperation("用户认证接口")
  @PostMapping("/userAuthentication")
  public Result<Object> userAuthentication(@RequestPart("sysAddRoleDTO") SysAddRoleDTO sysAddRoleDTO ,
                                            @RequestPart("personalAuthenticationDTO") PersonalAuthenticationDTO personalAuthenticationDTO,
                                             @RequestPart("enterpriseAuthenticationDTO") EnterpriseAuthenticationDTO enterpriseAuthenticationDTO,
                                              @RequestParam("imageFile")MultipartFile imageFile){

    //校验参数,
    String roleMessage = ValidateUtil.getModelValidationError(sysAddRoleDTO);
    String perMessage = ValidateUtil.getModelValidationError(personalAuthenticationDTO);
    String entMessage = ValidateUtil.getModelValidationError(enterpriseAuthenticationDTO);
    if (roleMessage != null && perMessage != null && entMessage != null){
      return Result.failed(ResultCode.FAIL,"认证信息填写有误,请检查后重试!");
    }

    return userAuthenticationService.addUserAuthentication(sysAddRoleDTO,personalAuthenticationDTO,enterpriseAuthenticationDTO,imageFile);
  }



  /**
     用户认证认证成功数据回显接口
   *@Param: null
   *@return: 用户认证数据
   *@Author: xxxx
   *@date: 2022/12/28
   */
  @GetMapping("/echoUserAuthentication")
  public Result<Object> echoUserAuthentication(){
    return userAuthenticationService.findUserAuthentication();
  }


  /**
   用户认证审核,展示认证详细信息接口
   *@Param:  userId
   *@return: 用户认证详细信息
   *@Author: xxxx
   *@date: 2022/12/28
   */
  @PostMapping("/userAuthenticationOne")
  public Result<Object> userAuthenticationOne(Long userId){
    if (userId == null){
      return Result.failed(ResultCode.FAIL,"用户信息不存在,请重试");
    }
    return userAuthenticationService.findUserAuthenticationOne(userId);
  }
}
